package cn.itcast.goods.book.dao;

import cn.itcast.goods.book.domain.Book;
import cn.itcast.goods.book.pager.Excpression;
import cn.itcast.goods.book.pager.PageBean;
import cn.itcast.goods.book.pager.PageConfig;
import cn.itcast.goods.user.DBConn.DbConn;
import cn.itcast.jdbc.TxQueryRunner;
import com.mysql.jdbc.Connection;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao {
    private QueryRunner queryRunner=null;
    private  PageBean<Book> findByCriteria(List<Excpression> excpressionList,int pc){
        /*
        1.得到ps：每页显示的数据条数
        2.得到tr:总的记录数
        3.得到BeanList
        4.创建pageBean
         */
        queryRunner=new TxQueryRunner();
        Connection conn= DbConn.getConnection();
      int ps= PageConfig.PAGE_SIZE;
      String sql=null;
      StringBuffer whereSql=new StringBuffer("where 1=1");
      List<Object> param=new ArrayList<Object>();
      PageBean<Book> pageBean=new PageBean<Book>();
      for (Excpression excpression:excpressionList)
      {
          whereSql.append(" and ").append(excpression.getName()).append(" ")
                  .append(excpression.getOperator()).append("");
          if (!excpression .equals("is null") ) {
              whereSql.append(" ? ");
              param.add(excpression.getValue());
          }
      }

      try {
          //得到总记录数
          sql="select count(*) from t_book"+whereSql;
          Number number=(Number) queryRunner.query(conn,sql,new ScalarHandler(),param.toArray());
          int tr=number.intValue();
          //得到beanList
          sql="select * from t_book "+whereSql+" order by orderBy limit ?,?";
          List<Book> bookList=queryRunner.query(conn,sql,new BeanListHandler<Book>(Book.class),param.toArray());
          //创建PageBean对象

          pageBean.setList(bookList);
          pageBean.setTr(tr);
          pageBean.setPc(pc);
          pageBean.setPs(ps);
      }catch (SQLException e)
      {
          throw  new RuntimeException(e);
      }
        return pageBean;
    }
   /* public  static  void main(String[] args){
        Excpression excpression=new Excpression();
        excpression.setName("name");
        excpression.setOperator("=");
        excpression.setValue("lelel");
        List<Excpression> excpressionList=new ArrayList<>();
        excpressionList.add(excpression);
        findByCriteria(excpressionList,10);
    }*/
   //按分类查询
    public PageBean<Book> findByCategory(String cid,int pc)
    {
        Excpression excpression=new Excpression();
        excpression.setName("cid");
        excpression.setOperator("=");
        excpression.setValue(cid);
        List<Excpression> list=new ArrayList<>();
        list.add(excpression);
      return findByCriteria(list,pc);
    }
}
